package com.tech.mapper.handler;

import com.tech.repository.session.GoodsSession;
import com.tech.util.FileUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BlobToImageHandler extends BaseTypeHandler<BufferedImage> {
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, BufferedImage parameter, JdbcType jdbcType) throws SQLException {
		String suffix = GoodsSession.CURRENT_NEW_IMAGE.getSuffix();
		System.out.println("suffix = " + suffix);
		try (ByteArrayInputStream bis = new ByteArrayInputStream(FileUtil.imageToByte(parameter, suffix))) {
			ps.setBinaryStream(i, bis);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public BufferedImage getNullableResult(ResultSet rs, String columnName) throws SQLException {
		byte[] bytes = rs.getBytes(columnName);
		if (bytes == null) return null;
		return FileUtil.byteToImage(bytes);
	}

	@Override
	public BufferedImage getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		byte[] bytes = rs.getBytes(columnIndex);
		if (bytes == null) return null;
		return FileUtil.byteToImage(bytes);
	}

	@Override
	public BufferedImage getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		byte[] bytes = cs.getBytes(columnIndex);
		if (bytes == null) return null;
		return FileUtil.byteToImage(bytes);
	}
}
